# -*- coding: UTF-8 -*-
# @Time : 2021-01-04 11:33
# @File : ExcelUtil.py
import xlrd
import os


# 自定义异常
class SheetTypeError:
    pass


class ExcelReader:
    def __init__(self, excel_file, sheet_by):
        pass
        if os.path.exists(excel_file):
            self.excel_file = excel_file
            self.sheet_by = sheet_by
            self._data = list()
        else:
            raise FileNotFoundError('文件不存在')

    def data(self):
        pass
        # 存在不读取，不存在读取
        if not self._data:
            workbook = xlrd.open_workbook(self.excel_file)
            if type(self.sheet_by) not in [int, str]:
                raise SheetTypeError('请输入Int or Str')
            elif type(self.sheet_by) == int:
                sheet = workbook.sheet_by_index(self.sheet_by)
            elif type(self.sheet_by) == str:
                sheet = workbook.sheet_by_name(self.sheet_by)
            # 读取sheet内容
            # 获取首行内容
            title = sheet.row_values(0)
            # 循环遍历
            for col in range(1, sheet.nrows):
                col_values = sheet.row_values(col)
                # 获取首行放入list
                self._data.append(dict(zip(title, col_values)))
        return self._data


if __name__ == '__main__':
    reader = ExcelReader('../data/data.xls', 'TestCases')
    print(reader.data())
